package com.yt.phone.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.yt.phone.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yt.phone.mapper.PhoneMapper;
import com.yt.phone.models.service.IPhoneService;
import com.yt.phone.models.bo.PhoneSaveBO;
import com.yt.phone.models.dto.PhoneDTO;


import java.util.List;


/**
 * 用户电话信息控制器
 *
 * @author lizicong
 * @Date 2025-11-17 09:11:31
 */
@DubboService
public class PhoneServiceImpl extends ServiceImpl<PhoneMapper, PhoneDTO> implements IPhoneService{

    @Resource
    private YmlConfig ymlConfig;
    
    @Resource
    private PhoneMapper phoneMapper;

    @Override
    public boolean add(PhoneSaveBO saveBO) {
        PhoneDTO dto = new PhoneDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    @Override
    public List<PhoneDTO> getphoneList() {
        List<PhoneDTO> phoneList = phoneMapper.selectList(null);
        return phoneList;
    }

    @Override
    public Page<PhoneDTO> getpagephoneList(int currentPage) {
        // 1. 校验页码（最小为1）
        if (currentPage < 1) {
            currentPage = 1;
        }
        // 2. 定义每页条数
        int pageSize = 5;
        // 3. 计算分页起始位置
        int offset = (currentPage - 1) * pageSize;
        RowBounds rowBounds = new RowBounds(offset, pageSize);

        EntityWrapper<PhoneDTO> wrapper = new EntityWrapper<>();
        wrapper.orderBy("create_time", false);
        // 4. 获取当前页数据（List类型）
        List<PhoneDTO> records = phoneMapper.selectPage(rowBounds, wrapper);

        // 5. 查询总记录数
        int totalCount = phoneMapper.selectCount(null);

        // 6. 手动封装 Page 对象（无需设置 pages，由 Page 自动计算）
        Page<PhoneDTO> page = new Page<>(currentPage, pageSize);
        page.setRecords(records); // 设置当前页数据
        page.setTotal(totalCount); // 设置总记录数（pages 会自动根据 total 和 size 计算）

        return page;
    }

    @Override
    public List<PhoneDTO> searchgetphoneList(String keyword) {
        Wrapper<PhoneDTO> wrapper = new EntityWrapper<>();
        wrapper.like("phone_number", keyword)
                .or()
                .like("phone_id", keyword);
        List<PhoneDTO> phoneList = phoneMapper.selectList(wrapper);
        return phoneList;
    }

    @Override
    public List<PhoneDTO> getPhoneListByUserId(Long userId) {
        Wrapper<PhoneDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userId);
         List<PhoneDTO> phoneList = phoneMapper.selectList(wrapper);
        return phoneList;
    }
}
